<template>
  <div class="wrapper bg-white h-full p-4 overflow-auto pl-6">
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="formState"
      :rules="rules"
      class="h-full flex flex-col items-start"
      label-suffix="："
      label-position="top"
      require-asterisk-position="right"
      @submit.prevent
    >
      <el-form-item prop="content" class="mb-1 flex-1 flex flex-col">
        <template #label>
          <span class="text-black">协议内容</span>
        </template>
        <div class="text-[12px] text-gray-400 -mt-1 mb-2 leading-[1.5]">
          用户端底部展示，及注册时用户勾选的协议
        </div>
        <BasicEditor
          ref="editorRef"
          v-model="formState.content"
          class="w-full overflow-auto"
        ></BasicEditor>
      </el-form-item>
      <el-divider />
      <el-button type="primary" @click="handleSave">保存配置</el-button>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

import { BasicEditor } from '@/components/application'
import ToastUtils from '@/utils/toast'

const formRef = ref<FormInstance>()
const loading = ref(false)
const rules: Record<string, FormItemRule[]> = {
  content: [
    {
      required: true,
      validator() {
        const content = editorRef.value?.getText()
        return !!content?.trim() || new Error('请输入协议内容')
      }
    }
  ]
}

const editorRef = ref<InstanceType<typeof BasicEditor>>()

const formState = reactive({
  content: ''
})

watch(
  () => formState.content,
  () => {
    setTimeout(() => {
      formRef.value?.validate()
    }, 0)
  }
)

onMounted(() => {
  loading.value = true
  configInfoApi({})
    .then(res => {
      formState.content = res.website_protocol?.user_agreement as string
    })
    .finally(() => {
      loading.value = false
    })
})

const handleSave = async () => {
  await formRef.value?.validate()
  loading.value = true
  try {
    await editConfigApi({
      website_protocol: {
        user_agreement: formState.content
      }
    })
    ToastUtils.success('修改成功')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
:deep(.quote-card) {
  @apply flex flex-col h-full overflow-hidden;
  .el-card__body {
    @apply flex flex-col items-start flex-1 overflow-hidden;
    .el-form-item__content {
      @apply flex-1 overflow-hidden;
    }
  }
}

:deep(.el-form-item) {
  width: 100%;
}

:deep(.basic-editor) {
  flex: 1;
  flex-basis: 0;
}

:deep(.el-form-item__content) {
  width: 100%;
  align-items: flex-start;
  flex-direction: column;
}
</style>
